package 实验四3;
import java.util.concurrent.*;

class SumCallable implements Callable<Integer> {
    private final int number;

    public SumCallable(int number) {
        this.number = number;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= number; i++) {
            sum += i;
        }
        return sum;
    }
}

public class Main {
    public static void main(String[] args) {
        int targetNumber = 10; // 计算 1 到 10 的总和

        // 创建 Callable 任务
        SumCallable sumCallable = new SumCallable(targetNumber);
        
        // 使用 FutureTask 包装 Callable
        FutureTask<Integer> futureTask = new FutureTask<>(sumCallable);
        
        // 创建并启动线程
        Thread thread = new Thread(futureTask);
        thread.start();

        try {
            // 获取计算结果（若未完成会阻塞）
            int result = futureTask.get();
            System.out.println("Sum from 1 to " + targetNumber + " is: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}